<template>
	<view class="layout">
		<view class="layout-header">
			<image src="https://dyfxmp-pre.lianlianlvyou.com/avatar/original/LL_IMAGE_e419625681a44c6ab5245d1c11be0c73.png" />
		</view>

		<view
			class="layout-main"
			:class="{ isWechat: isPageType }"
		>
			<view class="layout-main-avatar">
				<image src="https://dyfxmp-pre.lianlianlvyou.com/avatar/original/LL_IMAGE_2f5e50dca18e4cf085ba6c39afa82b8b.png" />
			</view>

			<view class="layout-main-name">
				<image src="https://dyfxmp-pre.lianlianlvyou.com/avatar/original/LL_IMAGE_a7e70f7d755c4d05964245009c96f5f9.png" />
			</view>

			<view class="layout-main-footer">
				<button v-if="isPageType" @click="getUserInfo" :loading="isLoading" :disabled="isLoading" :class="{ active: isLoading }">
					微信授权登录
				</button>

				<button
					v-else
					:loading="isLoading"
					:disabled="isLoading"
					:class="{ active: isLoading }"
					open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber"
				>
					手机号授权登录
				</button>
			</view>
		</view>

		<view class="layout-footer">
			登录即代表您同意
			<text @click="openPlatformPrivacyAgreement">《联联探客隐私协议》</text>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex';
import srorageKey from '@/utils/srorage/key';
import { getLocal, defaultImageUrl, setLocal } from '@/utils';
import { checkRegisterUrl } from '@/api/other';
import { getWxUuid, getUserToken } from '@/api/login';
import { loginOut, getSessionKeyExpired, InvitationCodeMistakeHintList } from '@/utils';
import Store from '@/store';

export default {
	name: 'invitaAuth',

	data() {
		return {
			isLoading: false,

			wxCode: null,
			invalidateCode: '',
			isPopupObject: {},
			isPageType: true,
			getAUseId: '',
			userInfo: {},
			temporaryUuid: '',
			props: 'wechat' // wechat 微信授权登录 phone 手机号授权登录
		};
	},

	computed: {
		// userInfo
		...mapGetters(['getToken']),
		userAvatar() {
			return require('@/static/logo.png');
		}
	},
	onLoad(options = {}) {
		let { scene, aUserId = 0, productId = '' } = options;
		let sceneAUserId = 0;
		let sceneProductId = '';
		if (scene) {
			const sceneParams = this.parseScene(scene);
			const { aUserId = 0, productId = '' } = sceneParams;
			sceneAUserId = aUserId;
			sceneProductId = productId;
		}

		this.getAUseId = sceneAUserId ? sceneAUserId : aUserId;
		this.getProductId = sceneProductId ? sceneProductId : productId;
		
		if (!this.getAUseId) {
			this.commonJump('index');
		}
	},
	created() {
		const { headUrl = '', nickName = '', phone = '' } = getLocal(srorageKey.userInfo) || {};
		const token = getLocal(srorageKey.AuthorizedToken);
		this.getWxCode();
		this.userInfo = { headUrl, nickName, phone };
		
		this.temporaryUuid = token;
	
		if (headUrl && nickName && phone && token) {
			setTimeout(() => {
				this.checkRegister(this.getAUseId, phone).then(() => {
					this.commonJump('dyAccount');
				});
			});
		} else if (headUrl && nickName && token) {
			this.isPageType = false;
			getSessionKeyExpired().then((status) => {
				!status && this.getWxCode();
			});
		} else {
			this.isPageType = true;
		}
	},
	methods: {
		commonJump(type = 'index') {
			const { getAUseId = '', getProductId = '' } = this;
			if (getProductId) {
				uni.reLaunch({
					url: `/tandianPage/ProductDetail?productId=${this.getProductId}`
				});
			} else {
				if (type === 'dyAccount') {
					uni.reLaunch({
						url: `/thirdManage/dyAccount`
					});
				} else {
					uni.switchTab({
						url: '/pages/tabBar/Index'
					});
				}
			}
		},
		getUserInfo() {
			const { wxCode, isLoading, invalidateCode } = this;

			if (isLoading) {
				return;
			}

			this.isLoading = true;

			uni.getUserProfile({
				desc: 'weixin',
				success: (res) => {
					const {
						userInfo: { avatarUrl, nickName }
					} = res;
					this.userInfo = { headUrl: avatarUrl, nickName };
					const formatNickName = nickName?.replace?.(/\s/g, '');
					getWxUuid({
						code: wxCode,
						invalidateCode,
						
						nickName: formatNickName || '微信用户',
						avatarUrl: avatarUrl || `${defaultImageUrl}logo.png`
					})
						.then((subRes) => {
							const { code, data } = subRes;

							if (code !== 200) {
								return;
							}
							this.temporaryUuid = data.token || '';

							const { userId, channelCount, ...otherParams } = data;
							Store.commit('changeUserInfo', {
								userId,
								channelCount,
								...otherParams
							});
							const { getAUseId = '', commonJump } = this;
							if (data.phone) {
								if (getAUseId) {
									this.checkRegister(getAUseId, data.phone).then(() => {
										commonJump('dyAccount');
									});
								} else {
									commonJump('index');
								}
							}
							/**
							 * userInvitationCodeResp: {
							 * 	codeUseStatus 邀请码使用提示：-1邀请码不存在；0可以使用；1使用成功；2已失效；3请勿重复使用邀请码；4已达使用上限
							 *  cycleType 福利周期：1每日；2每周；3每月；4每季度；5每年；9一次性；
							 *  download 邀请码使用成功后的下载次数
							 * }
							 */

							// this.$nextTick((e) => {
							// 	!this.$refs.DistributionInvitation.isPopup && loginOut(otherParams);
							// });
						})
						.catch((e) => {
							console.log(e);
							const { data = {} } = e || {};
							uni.showToast({
								title: data?.msg || '微信授权失败',
								icon: 'none'
							});
							this.getWxCode();
						})
						.finally((e) => {
							this.isLoading = false;
							this.$set(this, 'isPageType', false);
						});
				},
				fail: () => {
					this.isLoading = false;
				}
			});
		},

		getWxCode() {
			uni.login({
				provider: 'weixin',
				success: (res) => {
					this.wxCode = res.code;
				},
				fail: (res = {}) => {
					console.log(res);
					const { errMsg = '' } = res;

					uni.showToast({
						title: errMsg || '登录失败',
						icon: 'none'
					});
				}
			});
		},

		getPhoneNumber(params) {
			
			const {
				detail: { encryptedData, iv }
			} = params;
			const {
				getToken,
				userInfo: { nickName, headUrl }
			} = this;
		
			if (!encryptedData || !iv || this.isLoading) {
				return;
			}

			this.isLoading = true;
			
			getUserToken({
				iv,
				nickName,
				encryptedData,
				headerUrl: headUrl,
				token: getToken
			})
				.then((res) => {
					const { code, data } = res;
					
					if (code !== 200) {
						return;
					}
					const { userId, channelCount, ...otherParams } = data;

					Store.commit('changeUserInfo', {
						userId,
						channelCount,
						...otherParams
					});
					this.checkRegister(this.getAUseId, data.phone).then(() => {
						this.commonJump('dyAccount');
					});
				})
				.catch((err) => {
					console.log(err);
				})
				.finally(() => {
					this.isLoading = false;
				});
		},

		openComeBack() {
			uni.navigateBack({
				delta: 1
			});
		},

		openPlatformPrivacyAgreement() {
			const webView = `${defaultImageUrl}webView/PlatformPrivacyAgreement.html`;
			const url = `/tandianPage/CommonWebView?webView=${webView}`;

			uni.navigateTo({
				url
			});
		},

		clickCallBack(params) {
			loginOut(params);
		},
		parseScene(scene) {
			try {
				const res = {};
				const str = decodeURIComponent(scene);
				const arr = str.split('&');
				arr.forEach((e) => {
					const keyValPairArr = e.split('=');
					res[keyValPairArr[0]] = keyValPairArr[1];
				});
				return res;
			} catch (e) {
				return {};
			}
		},

		// 检查注册与否
		checkRegister(param = '', getPhone = '') {
			return new Promise((resolve, reject) => {
				const { phone = '' } = getLocal(srorageKey.userInfo) || {};
				checkRegisterUrl({ mobile: phone || getPhone, aUserId: param })
					.then((res = {}) => {
						// 是否已经注册：0-未注册，1-已注册
						const { blnRegister = '', headImgUrl = '', nickName = '' } = res.data || {};
						
						if (blnRegister || !headImgUrl || !nickName) {
							this.commonJump('index');  
						} else {
							this.checkResult = blnRegister; // 暂时未用
							this.agentInfo = { headImgUrl, nickNameA: nickName };
							resolve();
						}
					})
					.catch((err = {}) => {
						const { msg = '' } = err.data || {};
						uni.showToast({
							title: msg || '网络错误',
							icon: 'none'
						});
						reject();
					});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	height: 100vh;
	background: #fff;
	image {
		width: 100%;
		height: 100%;
	}
	&-header {
		height: 480rpx;
	}

	&-main {
		width: calc(100% - 80rpx);
		margin: -180rpx auto 40rpx;
		&-avatar {
			width: 200rpx;
			height: 200rpx;
			margin: -68rpx auto 20rpx;
		}

		&-name {
			width: 328rpx;
			height: 84rpx;
			margin: 0 auto;
		}

		&-footer {
			margin-top: 260rpx;
			button{
				@include Db_newButton();
			}
		}
	}

	&-footer {		
		color: #999;
		text-align: center;
		font-size: 24rpx;
		text {
			color: $themeColor;
		}
	}
}
</style>
